import Cookies from 'js-cookie'
import qs from 'qs'
import { MikeBannerType } from '@/utils/consts'

export default {
  data () {
    /* eslint-disable */
    return {
      mikeNetworkBase: window.SITE_CONFIG["mike_apiURL"],
      // 设置属性
      mixinViewModuleOptions: {
        
        activatedIsNeed: true, // 此页面是否在激活（进入）时，调用查询数据列表接口？
        getDataListURL: "", // 数据列表接口，API地址
        getDataListIsPage: false, // 数据列表接口，是否需要分页？
        deleteURL: "", // 删除接口，API地址
        deleteIsBatch: false, // 删除接口，是否需要批量？
        deleteIsBatchKey: "id", // 删除接口，批量状态下由那个key进行标记操作？比如：pid，uid...
        exportURL: "" // 导出接口，API地址
      },
      // 默认属性
      dataForm: {}, // 查询条件
      dataList: [], // 数据列表
      order: "", // 排序，asc／desc
      orderField: "", // 排序，字段
      page: 1, // 当前页码
      limit: 10, // 每页数
      total: 0, // 总条数
      dataListLoading: false, // 数据列表，loading状态
      dataListSelections: [], // 数据列表，多选项
      addOrUpdateVisible: false // 新增／更新，弹窗visible状态
    };
    /* eslint-enable */
  },
  activated () {
    if (this.mixinViewModuleOptions.activatedIsNeed) {
      this.getDataList()
    }
  },
  methods: {
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true

      this.$http
        .post(
          (this.mikeNetworkBase) +
            this.mixinViewModuleOptions.getDataListURL,
          {
            // order: this.order,
            // orderField: this.orderField,
            currentPage: this.mixinViewModuleOptions.getDataListIsPage ? this.page : undefined,
            pageSize: this.mixinViewModuleOptions.getDataListIsPage ? this.limit : undefined,
            ...this.dataForm
          }
        )
        .then(({ data: res }) => {
          this.dataListLoading = false

          if (res.code !== 200) {
            this.dataList = []
            this.total = 0
            return this.$message.error(res.msg)
          }
          this.dataList = this.handleResponseListData(res.data)

          let totalCounts = res.totalCounts
            ? res.totalCounts
            : this.dataList && this.dataList.length > 0
              ? this.dataList[0].totalCounts
              : 0
          this.total = totalCounts
          // this.dataList = this.mixinViewModuleOptions.getDataListIsPage ? res.data.list : res.data
          // this.total = this.mixinViewModuleOptions.getDataListIsPage ? res.data.total : 0
        })
        .catch(() => {
          this.dataListLoading = false
        })
    },

    handleResponseListData (data) {
      return data
    },
    // 多选
    dataListSelectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 排序
    dataListSortChangeHandle (data) {
      if (!data.order || !data.prop) {
        this.order = ''
        this.orderField = ''
        return false
      }
      this.order = data.order.replace(/ending$/, '')
      this.orderField = data.prop.replace(/([A-Z])/g, '_$1').toLowerCase()
      this.getDataList()
    },
    // 分页, 每页条数
    pageSizeChangeHandle (val) {
      this.page = 1
      this.limit = val
      this.getDataList()
    },
    // 分页, 当前页
    pageCurrentChangeHandle (val) {
      this.page = val
      this.getDataList()
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.dataForm.id = id
        this.$refs.addOrUpdate.init()
      })
    },
    // 删除
    deleteHandle (id) {
      if (
        this.mixinViewModuleOptions.deleteIsBatch &&
        !id &&
        this.dataListSelections.length <= 0
      ) {
        return this.$message({
          message: this.$t('prompt.deleteBatch'),
          type: 'warning',
          duration: 500
        })
      }
      this.$confirm(
        this.$t('prompt.info', { handle: this.$t('delete') }),
        this.$t('prompt.title'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })

          this.$http
            .post(
              `${this.mikeNetworkBase
              }${this.mixinViewModuleOptions.deleteURL}${
                this.mixinViewModuleOptions.deleteIsBatch ? '' : '/' + id
              }`,
              this.mixinViewModuleOptions.deleteIsBatch
                ? {
                  data: id
                    ? [id]
                    : this.dataListSelections.map(
                      item =>
                        item[this.mixinViewModuleOptions.deleteIsBatchKey]
                    )
                }
                : {}
            )
            .then(({ data: res }) => {
              if (res.code !== 200) {
                return this.$message.error(res.msg)
              }
              this.$message({
                message: this.$t('prompt.success'),
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.getDataList()
                }
              })
            })
            .catch(() => {})
            .finally(() => {
              loading.close()
            })
        })
        .catch(() => {})
    },
    // 导出
    exportHandle () {
      var params = qs.stringify({
        token: Cookies.get('token'),
        ...this.dataForm
      })
      window.location.href = `${window.SITE_CONFIG['apiURL']}${this.mixinViewModuleOptions.exportURL}?${params}`
    },

    /**
     * Custom Mike only methods
     * */

    addToBanner (model) {
      return this.addRemoveBanner(model.showTypes, model, false)
    },
    removeFromBanner (model) {
      return this.addRemoveBanner(model.showTypes, model, true)
    },

    addRemoveBanner (type, model, isRemove) {
      return new Promise(resolve => {
        if (!model || !model.id || model.id.length <= 0) {
          return
        }

        if (model.requesting) {
          return
        }
        model.requesting = true

        let url = ''
        let params = {}
        if (type === MikeBannerType.Recipe) {
          url = 'midea/menu/collection/content/menurecommend/set'
          params = {
            setOrDel: isRemove ? 1 : 0,
            menuIds: [model.id],
            sn8: this.sn8
          }
        }

        if (type === MikeBannerType.Collection) {
          url = 'midea/menu/collection/content/recommend/setdel'
          params = {
            setOrDel: isRemove ? 1 : 0,
            collectionIds: [model.id],
            sn8: this.sn8
          }
        }
        if (type === MikeBannerType.Activity) {
          url = 'midea/menu/piclink/setrecommend'
          params = {
            flag: isRemove ? 1 : 0,
            picLinkIds: [model.id],
            sn8: this.sn8
          }
        }

        url = `${
          this.mikeNetworkBase
        }${url}`

        this.$http
          .post(url, params)
          .then(({ data: res }) => {
            if (res.code !== 200) {
              this.$message.error(isRemove ? '删除失败' : '添加失败')
              resolve()
              return
            }
            this.$message.success(isRemove ? '删除成功' : '添加成功')

            this.$emit('refreshDataList')
            if (this.reload) {
              this.reload()
            }
            resolve()
          })
          .finally(() => {
            model.requesting = false
          })
      })
    }
  }
}
